package com.hotelsystem.realm;

import com.hotelsystem.pojo.Employee;
import com.hotelsystem.service.EmployeeService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;

import javax.annotation.Resource;


public class EmpRealm extends AuthorizingRealm {
    /**
     * 执行授权逻辑
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行授权逻辑");
        //给资源进行授权
        SimpleAuthorizationInfo simpleAuthenticationInfo = new SimpleAuthorizationInfo();

        //获取当前登录的用户
        Subject subject = SecurityUtils.getSubject();
        Employee employee = (Employee) subject.getPrincipal();
        System.out.println("角色Id"+employee.getRole().getRoleId());
        //System.out.println("角色RoleName"+employee.getRole().getRoleName());
        //拿到授权Id
        String permission = "emp:common";
        if (employee.getRole().getRoleId() ==1){
            permission = "emp:supper";
        }
        if (employee.getRole().getRoleId() == 2){
            permission = "emp:admin";
        }

       // PermissionsAuthorizationFilter permissionsAuthorizationFilter = new PermissionsAuthorizationFilter();
        simpleAuthenticationInfo.addStringPermission(permission);
        return simpleAuthenticationInfo;
    }


    @Resource(name = "employeeServiceImpl")
    private EmployeeService employeeService;
    /**
     * 执行认证逻辑
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("执行认证逻辑");
        //判断用户名和密码
        //1.判断用户名
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        Employee employee = null;
        try {
            employee = employeeService.getEmpInfoByuserName(token.getUsername());
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (employee == null){
            //用户名不存在
            return null;
        }
        return new SimpleAuthenticationInfo(employee,employee.getPassword(),"");
    }
}
